import { CommonModal } from "@/pages/OrderModule/common/components/CommonModal";
import { CommonTable } from "@/pages/OrderModule/common/components/CommonTable";
import CommonLoading from "@/components/CommonLoading";
import Typography from "@/pages/OrderModule/common/components/Typography";
import { Alert, Button, Space, message, ConfigProvider, Image } from "antd";
import { useState, useEffect, useRef } from "react";
import { getUnMatchGoodsOp, getInfoCount } from "../../../../services";
import GoodsMatchDrawer from "@/pages/GoodsModule/systemGoods/components/Actions/GoodsMatchDrawer/index";
import CommonPagination from "@/components/CommonPagination";
import { getInfoGoodsSku } from "@/pages/GoodsModule/systemGoods/service.js";
import SearchForm from "./SearchForm";

/** 未匹配商品明细 */
function UnmatchedProductDetailsModal({ handleOk, handleCancel }) {
	const [loading, setLoading] = useState(false);
	const [data, setData] = useState([]);
	const [matchInfo, setMatchInfo] = useState({});
	const [selectRowKeys, setSelectRowKeys] = useState([]); //勾选
	const [selectRows, setSelectRows] = useState([]); //勾选
	const [num, setNum] = useState(0);
	const [query, setQuery] = useState({});

	const [pagination, setPages] = useState({
		current: 1,
		total: 0,
		pageSize: 500,
		showQuickJumper: true,
		pageSizeOptions: [100, 200, 500, 2000]
	});

	const orderIds = useRef([]);

	useEffect(() => {
		getSourceFunc();
	}, [pagination, query]);

	useEffect(() => {
		handleGetInfoCount();
	}, []);

	//查询供应商匹配统计
	const handleGetInfoCount = async () => {
		const { success, data } = await getInfoCount();
		if (success) {
			setNum(data);
		}
	};

	//获取列表数据
	const getSourceFunc = async () => {
		setLoading(true);
        setSelectRowKeys([]);
		const { data, success } = await getUnMatchGoodsOp({
			stateArr: [10, 30],
			isMatch: 0,
			...query,
			pageNum: pagination.current,
			pageSize: pagination.pageSize
		});
		setLoading(false);
		if (success && data?.records) {
			// const obj = {};
			//  data.records.map(item=>{
			//   !item.payState && item.goodsList.map(child=>{
			//     if(child.isMatch) return

			//      if(obj[child.sysGoodsId]){
			//       obj[child.sysGoodsId].orderIds.push(item.id);
			//      }else{
			//       obj[child.sysGoodsId]= {
			//         goodsInfo: child,
			//         orderIds: [item.id]
			//       }
			//      }
			//   })
			//  })
			//   const arr = [];
			//   Object.keys(obj).map(item=>{
			//     arr.push({
			//       ...obj[item].goodsInfo,
			//       orderIds: [...new Set(obj[item]?.orderIds || [])]
			//     })
			//   })
			//   console.log(arr,'arr')
			pagination.total = data.total;
			setData(
				data?.records.map(item => {
					item.orderIds = item.orderIds.split(",")?.map(child => Number(child));
					return item;
				})
			);
		} else {
			setData([]);
		}
	};

	const handleClick = async (defaultTab, record) => {
		const { data, success } = await getInfoGoodsSku({ id: record.sysGoodsId });
		if (data && success) {
			setMatchInfo({
				defaultTab,
				data: [
					{
						...record,
						// availableInventory: record.availableGoodsNum,
						...(data || {}),
						orderIds: record.orderIds
					}
				]
			});
		}
	};

	//供应商匹配
	const handleBatchMatch = () => {
		if (selectRowKeys.length) {
			// const arr = [];
			// selectRowKeys.forEach(z => {
			// 	arr.push({ skuId: z });
			// });
			setMatchInfo({
				defaultTab: "供应商匹配",
				data: selectRows
			});
		} else {
			message.info("请勾选商品");
		}
	};

	const columns = [
		{
			title: "序号",
			dataIndex: "name",
			key: "name",
			width: 60,
			render(text, record, index) {
				return index + 1;
			}
		},
		{
			title: "图片",
			dataIndex: "orderGoods",
			key: "orderGoods",
			width: 80,
			render(value, goodsInfo) {
				return (
					<div style={{ display: "flex" }}>
						<Image
							src={goodsInfo.sysGoodsImage || goodsInfo.goodsImage}
							style={{ width: "48px", borderRadius: "4px", marginRight: "8px" }}
						/>
					</div>
				);
			}
		},
		{
			title: "商品名称",
			dataIndex: "orderGoods",
			key: "orderGoods",
			width: 180,
			render(value, goodsInfo) {
				return (
					<div style={{ display: "flex" }}>
						<div>
							<div className="textOverflowMultiTwo" style={{ marginBottom: "3px" }}>
								{goodsInfo.sysGoodsName || goodsInfo.goodsName}
							</div>
						</div>
					</div>
				);
			}
		},
		{
			title: "颜色规格",
			dataIndex: "orderGoods",
			key: "orderGoods",
			width: 180,
			render(value, goodsInfo) {
				return (
					<div style={{ display: "flex" }}>
						<div>
							<div style={{ color: "#7C7E82", lineHeight: "16px" }}>{goodsInfo.sysGoodsSpec || goodsInfo.goodsSpec}</div>
						</div>
					</div>
				);
			}
		},
		{
			title: "商品编码",
			dataIndex: "sysSkuCode",
			key: "sysSkuCode",
			width: 90
		},
		{
			title: "款式编码",
			dataIndex: "sysSpuCode",
			key: "sysSpuCode",
			width: 120
		},
		{
			title: "商品简称",
			dataIndex: "goodsAbbreviation",
			key: "goodsAbbreviation",
			width: 120
		},
		{
			title: "成本价",
			dataIndex: "sysGoodsPrice",
			key: "sysGoodsPrice",
			width: 120
		},
		{
			title: "零售价",
			dataIndex: "goodsSnackPrices",
			key: "goodsSnackPrices",
			width: 120
		},
		{
			title: "市场价|吊牌价",
			dataIndex: "goodsMarketPrice",
			key: "goodsMarketPrice",
			width: 120
		},
		{
			title: "重量",
			dataIndex: "goodsWeight",
			key: "goodsWeight",
			width: 120
		},
		{
			title: "操作",
			dataIndex: "age1",
			key: "age1",
            fixed: 'right',
			width: 280,
			render(text, record, index) {
				return (
					<Space size="small">
						<Button type="link" onClick={() => handleClick("精准匹配", record)}>
							匹配商品
						</Button>
						<Button type="link" onClick={() => handleClick("供应商匹配", record)}>
							供应商匹配
						</Button>
						<Button type="link" onClick={() => handleClick("单个商品的智能匹配", record)}>
							智能匹配
						</Button>
					</Space>
				);
			}
		}
	];

	const onCancel = () => {
		if (orderIds.current?.length) {
			handleOk(1, orderIds.current);
		} else {
			handleCancel();
		}
	};

	//商品匹配props
	const goodsMatchDrawerProps = {
		isSkuType: true,
		// isOrderGoods: selectRowKeys.length ? false: true,
        isOrderGoods: true,
		defaultTab: matchInfo.defaultTab,
		data: matchInfo.data,
		onCancel(ids) {
			if (ids?.length) {
				orderIds.current.push(...ids);
				setPages({ ...pagination });
			}
			setMatchInfo({});
            setSelectRowKeys([]);
			setSelectRows([]);
		    handleGetInfoCount();
		}
	};

	//表单区
	const searchContentProps = {
		query,
		queryChangeFunc(value, bool) {
			//查询 重制
			if (bool) {
				setQuery({});
			} else {
				setQuery({ ...query, ...value });
			}
		},
		handleSetQuery(val) {
			setQuery({ ...query, ...val });
		}
	};

	const pageProps = {
		pagination,
		handleChange(current, size) {
			const obj = { ...pagination, current, pageSize: size };
			setPages(obj);
		}
	};

	return (
		<CommonModal
			title={{
				title: (
					<div>
						未匹配商品明细（<span className="common-color9">{num}</span>）
					</div>
				)
			}}
			open={true}
			width="1280px"
			zIndex={600}
			footer={[
				<Button key="close" onClick={onCancel}>
					关闭
				</Button>
			]}
			onCancel={onCancel}
		>
			<Alert showIcon message={<Typography as="s1">待审核和异常状态的订单，所有未匹配的商品明细</Typography>} />
			<SearchForm {...searchContentProps} />
			<Button onClick={handleBatchMatch} style={{ marginRight: "8px", height: "32px", fontSize: "12px" }}>
				供应商匹配
			</Button>
			<CommonTable
				rowSelection={{
					selectedRowKeys: selectRowKeys,
					onChange: (selectedRowKeys, selectRows) => {
						setSelectRowKeys(selectedRowKeys);
						setSelectRows(selectRows);
					}
				}}
				rowKey="sysGoodsId"
				bordered
				style={{ marginTop: 16 }}
				dataSource={data}
				columns={columns}
				pagination={false}
				scroll={{ y: "28vh" }}
			/>
			<div style={{ marginTop: "8px" }}>
				<CommonPagination {...pageProps} />
			</div>
			{matchInfo.defaultTab && (
				<ConfigProvider componentSize="small">
					<GoodsMatchDrawer {...goodsMatchDrawerProps} />
				</ConfigProvider>
			)}
			<CommonLoading loading={loading} />
		</CommonModal>
	);
}

export default UnmatchedProductDetailsModal;
